package com.hou.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class Watcher01 {
    /**
     * zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.171.128:2181,192.168.171.129:2181,192.168.171.130:2181";
    /**
     * session超时时间
     */
    static final int SESSION_OUTTIME = 5000;//ms

    public static void main(String[] args) throws Exception {
        //重试策略：初试时间为1s 重试10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        //通过工厂建立连接
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(CONNECT_ADDR) //连接地址
                .sessionTimeoutMs(SESSION_OUTTIME)
                .retryPolicy(retryPolicy)//重试策略
                .build();
        curatorFramework.start();
        //监听子节点:建立一个PathChildrenCache缓存,第三个参数为是否接受节点数据内容 如果为false则不接受
        PathChildrenCache cache = new PathChildrenCache(curatorFramework, "/father", true);
        //在初始化的时候就进行缓存监听
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        //监听子节点的新增,修改,删除
        cache.getListenable().addListener((cf, event) -> {//PathChildrenCacheListener实现类
            switch (event.getType()) {
                case CHILD_ADDED:
                    System.out.println("添加子节点 :" + event.getData().getPath());
                    break;
                case CHILD_UPDATED:
                    System.out.println("更新子节点 :" + event.getData().getPath());
                    break;
                case CHILD_REMOVED:
                    System.out.println("删除子节点 :" + event.getData().getPath());
                    break;
                default:
                    break;
            }
        });
        //创建本身节点不发生变化
        curatorFramework.create().forPath("/father", "init".getBytes());

        //添加子节点
        Thread.sleep(1000);
        curatorFramework.create().forPath("/father/c1", "c1内容".getBytes());
        Thread.sleep(1000);
        curatorFramework.create().forPath("/father/c2", "c2内容".getBytes());

        //修改子节点
        Thread.sleep(1000);
        curatorFramework.setData().forPath("/father/c1", "c1更新内容".getBytes());

        //删除子节点
        Thread.sleep(1000);
        curatorFramework.delete().forPath("/father/c2");

        //删除本身节点
        Thread.sleep(1000);
        curatorFramework.delete().deletingChildrenIfNeeded().forPath("/father");

        Thread.sleep(Integer.MAX_VALUE);

    }
}
